package com.bhs.sansonglogistics.ui.quality;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StrikethroughSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.bean.AdvancePayment;
import com.bhs.sansonglogistics.bean.LinePromo;
import com.bhs.sansonglogistics.bean.MenuBean;
import com.bhs.sansonglogistics.bean.PromotionPrice;
import com.bhs.sansonglogistics.bean.event.OrderEvent;
import com.bhs.sansonglogistics.bean.event.PayStatus;
import com.bhs.sansonglogistics.dialog.ConfirmationDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.dialog.UpgradeRecommendationDialog;
import com.bhs.sansonglogistics.net.Config;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.LinePromotionAdapter;
import com.bhs.sansonglogistics.ui.adapter.MenuAdapter;
import com.bhs.sansonglogistics.ui.adapter.PrivilegeAdapter;
import com.bhs.sansonglogistics.ui.other.WebViewActivity;
import com.bhs.sansonglogistics.ui.wallet.PayDeskActivity;
import com.bhs.sansonglogistics.ui.waybill.TruckPositioningHistoryActivity;
import com.bhs.sansonglogistics.utils.DateUtils;
import com.bhs.sansonglogistics.utils.FastCilckOneUtil;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 专线推广
 */
public class PrivateLinePromotionActivity extends BaseActivity implements View.OnClickListener, NetCallBack {

    private TextView mTvGoldCard;
    private TextView mTvSilverCard;
    private RecyclerView mRvList;
    private CheckBox mCbAgreement;
    private Button mBtnSubmit;
    private int promotionType = 1;//1金卡  2银卡
    private LinePromotionAdapter mAdapter;
    private List<PromotionPrice> goldList = new ArrayList<>();
    private List<PromotionPrice> silverList = new ArrayList<>();
    private int money = -1;
    private int line_id;
    private String type;
    private int promote_type;
    private int status = 0;//0未开放  1开通金卡  2开通银卡
    private String btnText;
    private FrameLayout mLlGoldCard;
    private FrameLayout mLlSilverCard;
    private RecyclerView mRvPrivilege;
    private TextView mTvDivision;
    private TextView mTvExpirationTime;
    private ImageView mIvGoldLabel;
    private ImageView mIvSilverLabel;
    private List<PromotionPrice> upgradeList = new ArrayList<>();
    private int mPosition = 0;
    private int payType = 2;//2购买  12续费

    @Override
    public int initLayout() {
        return R.layout.activity_private_line_promotion;
    }


    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        line_id = getIntent().getIntExtra("line_id", 0);
        promote_type = getIntent().getIntExtra("promote_type", 0);
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("专线推广");
        mTvGoldCard = findViewById(R.id.tv_gold_card);
        mTvSilverCard = findViewById(R.id.tv_silver_card);
        mRvList = findViewById(R.id.rv_list);
        mCbAgreement = findViewById(R.id.cb_agreement);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mRvPrivilege = findViewById(R.id.rv_privilege);
        mTvDivision = findViewById(R.id.tv_division);
        mTvExpirationTime = findViewById(R.id.tv_expiration_time);
        findViewById(R.id.tv_record).setOnClickListener(this);

        mLlGoldCard = findViewById(R.id.ll_gold_card);
        mLlSilverCard = findViewById(R.id.ll_silver_card);
        mLlGoldCard.setOnClickListener(this);
        mLlSilverCard.setOnClickListener(this);
        mIvGoldLabel = findViewById(R.id.iv_gold_label);
        mIvSilverLabel = findViewById(R.id.iv_silver_label);

    }

    private UpgradeRecommendationDialog recommendationDialog;

    @Override
    public void initData() {
        if (promote_type > 0) {
            String time = DateUtils.getYearMonthDay(getIntent().getIntExtra("expirationTime", 0));
            mTvExpirationTime.setText(String.format("您的%s推广服务将在%s到期哦！快来续费或升级吧~",MyUtils.getPromotionType(promote_type) ,time));
        } else {
            findViewById(R.id.ll_expiration_time).setVisibility(View.GONE);
        }
        goldList.add(new PromotionPrice("年度推广", "1", "金卡推广"));
        goldList.add(new PromotionPrice("半年推广", "2", "金卡推广"));
        goldList.add(new PromotionPrice("季度推广", "3", "金卡推广"));
        mAdapter = new LinePromotionAdapter(R.layout.item_promotion, goldList);
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new GridLayoutManager(mActivity, 3));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!TextUtils.isEmpty(mAdapter.getData().get(position).getPresentPrice())) {
                    select(position);
                }
            }
        });
        String str = "我已阅读并同意《专线推广协议》";
        SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(str);
        ClickableSpan clickableSpanOne = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, WebViewActivity.class).putExtra("url", Config.getPromotion()).putExtra("title", "专线推广协议"));
            }

            @Override
            public void updateDrawState(TextPaint paint) {
                paint.setColor(Color.parseColor("#485EF4"));
                // 设置下划线 true显示、false不显示
                paint.setUnderlineText(false);
            }
        };
        spannableBuilder.setSpan(clickableSpanOne, 7, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mCbAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        mCbAgreement.setText(spannableBuilder);

        networkRequest(netApi.get_promote_config_info(), this);
        privilege();
    }

    private void select(int position) {
        mPosition = position;
        for (PromotionPrice datum : mAdapter.getData()) {
            datum.setCheck(false);
        }
        mAdapter.getData().get(position).setCheck(true);
        mAdapter.notifyDataSetChanged();
        money = Integer.parseInt(mAdapter.getData().get(position).getPresentPrice());
        type = mAdapter.getData().get(position).getType();
        mBtnSubmit.setText(String.format("%s￥%s", btnText, mAdapter.getData().get(position).getPresentPrice()));
    }

    List<MenuBean> menuBeanGoldList = new ArrayList<>();
    List<MenuBean> menuBeansSliverList = new ArrayList<>();
    private PrivilegeAdapter privilegeAdapter;

    private void privilege() {
        menuBeanGoldList.add(new MenuBean("增加专线曝光率+200%", R.mipmap.ic_gold1));
        menuBeanGoldList.add(new MenuBean("增加企业曝光率+300%", R.mipmap.ic_gold2));
        menuBeanGoldList.add(new MenuBean("访问人数增加+180%", R.mipmap.ic_gold3));
        menuBeanGoldList.add(new MenuBean("订单增量+150%", R.mipmap.ic_gold4));
        privilegeAdapter = new PrivilegeAdapter(menuBeanGoldList);
        menuBeansSliverList.add(new MenuBean("增加专线曝光率+160%", R.mipmap.ic_sliver1));
        menuBeansSliverList.add(new MenuBean("增加企业曝光率+200%", R.mipmap.ic_sliver2));
        menuBeansSliverList.add(new MenuBean("访问人数增加+130%", R.mipmap.ic_sliver3));
        menuBeansSliverList.add(new MenuBean("订单增量+110%", R.mipmap.ic_sliver4));

        mRvPrivilege.setAdapter(privilegeAdapter);
        mRvPrivilege.setLayoutManager(new LinearLayoutManager(this));
    }

    @SuppressLint({"NonConstantResourceId", "NotifyDataSetChanged"})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_gold_card:
                if (promotionType != 1) {
                    if (!MyUtils.isEmpty(silverList)) {
                        for (PromotionPrice promotionPrice : silverList) {
                            promotionPrice.setCheck(false);
                        }
                    }
                    promotionType = 1;
                    mAdapter.setPromotionType(promotionType);
                    mAdapter.setNewData(goldList);
                    mLlGoldCard.setBackgroundResource(R.drawable.bg_top_white_16);
                    mLlSilverCard.setBackground(null);
                    mTvGoldCard.setTypeface(Typeface.DEFAULT_BOLD);
                    mTvSilverCard.setTypeface(Typeface.DEFAULT);
                    privilegeAdapter.setNewData(menuBeanGoldList);
                    privilegeAdapter.setType(promotionType);
                    mTvDivision.setTextColor(Color.parseColor("#9E8004"));
                    if (status == 2) {
                        btnText = "立即升级";
                    }
                    select(0);
                }
                break;
            case R.id.ll_silver_card:
                if (promotionType != 2) {
                    if (!MyUtils.isEmpty(goldList)) {
                        for (PromotionPrice promotionPrice : goldList) {
                            promotionPrice.setCheck(false);
                        }
                    }
                    promotionType = 2;
                    mAdapter.setPromotionType(promotionType);
                    mAdapter.setNewData(silverList);
                    mLlSilverCard.setBackgroundResource(R.drawable.bg_top_white_16);
                    mLlGoldCard.setBackground(null);
                    mTvSilverCard.setTypeface(Typeface.DEFAULT_BOLD);
                    mTvGoldCard.setTypeface(Typeface.DEFAULT);
                    privilegeAdapter.setNewData(menuBeansSliverList);
                    privilegeAdapter.setType(promotionType);
                    mTvDivision.setTextColor(Color.parseColor("#535C73"));
                    if (status == 2) {
                        btnText = "立即续费";
                    }
                    select(0);
                }
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.tv_record:
                startActivity(new Intent(PrivateLinePromotionActivity.this, LinePromotionListActivity.class));
                break;
        }
    }

    private ConfirmationDialog confirmationDialog;

    private void submit() {

        if (FastCilckOneUtil.isFastClick()) {
            return;
        }
        if (money == -1) {
            ToastUtil.show("请选择推广类型");
            return;
        }
        if (!mCbAgreement.isChecked()) {
            ToastUtil.show("请勾选同意推广协议");
            return;
        }

        if (btnText.equals("立即升级")) {
            if (confirmationDialog == null) {
                confirmationDialog = new ConfirmationDialog(this);
            }
            confirmationDialog.show();
            confirmationDialog.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    payType = 2;
                    networkRequest(netApi.create_promote_order(line_id, type), PrivateLinePromotionActivity.this, 666);
                }
            });
        } else if (btnText.equals("立即续费")) {
            if (status == 2 && !MyUtils.isEmpty(goldList)) {
                if (recommendationDialog == null) {
                    recommendationDialog = new UpgradeRecommendationDialog(PrivateLinePromotionActivity.this);
                    recommendationDialog.setMyClickListener(new MyClickListener2() {
                        @Override
                        public void onClick(String id, String info) {
                            money = Integer.parseInt(info);
                            if (Integer.parseInt(id) < 5) {
                                payType = 2;
                                networkRequest(netApi.create_promote_order(line_id, id), PrivateLinePromotionActivity.this, 666);
                            } else {
                                payType = 12;
                                networkRequest(netApi.create_renew_promote_order(line_id, id), PrivateLinePromotionActivity.this, 666);
                            }

                        }
                    });
                    upgradeList.addAll(goldList);
                    for (PromotionPrice promotionPrice : upgradeList) {
                        promotionPrice.setCheck(false);
                    }
                    upgradeList.add(0, mAdapter.getData().get(mPosition));
                } else {
                    for (PromotionPrice promotionPrice : upgradeList) {
                        promotionPrice.setCheck(false);
                    }
                    upgradeList.set(0, mAdapter.getData().get(mPosition));
                }

                recommendationDialog.show();
                recommendationDialog.setNewData(upgradeList);
            } else {
                payType = 12;
                networkRequest(netApi.create_renew_promote_order(line_id, type), PrivateLinePromotionActivity.this, 666);
            }
        } else {
            networkRequest(netApi.create_promote_order(line_id, type), this, 666);
        }

    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            LinePromo linePromo = new Gson().fromJson(json, LinePromo.class);
            if (linePromo.isStatus()) {
                LinePromo.DataDTO data = linePromo.getData();
                if (promote_type == 0) {
                    btnText = "立即推广";
                } else if (promote_type > 0 && promote_type < 5) {
                    btnText = "立即续费";
                    status = 1;
                    mLlSilverCard.setVisibility(View.GONE);
                    mIvGoldLabel.setVisibility(View.VISIBLE);
                } else if (promote_type > 5) {
                    if (linePromo.getData().getLinePromote_gold_switch().equals("1")) {
                        btnText = "立即升级";
                    } else {
                        btnText = "立即续费";
                    }
                    status = 2;
                }
                mBtnSubmit.setText(btnText);
                //金卡价格
                goldList.get(0).setOriginalCost(data.getLinePromote_gold_annual_originalMoney());
                goldList.get(0).setPresentPrice(data.getLinePromote_gold_annual_nowMoney());
                goldList.get(1).setOriginalCost(data.getLinePromote_gold_semi_originalMoney());
                goldList.get(1).setPresentPrice(data.getLinePromote_gold_semi_nowMoney());
                goldList.get(2).setOriginalCost(data.getLinePromote_gold_quarter_originalMoney());
                goldList.get(2).setPresentPrice(data.getLinePromote_gold_quarter_nowMoney());
                if (data.getLinePromote_gold_quarter_switch().equals("0")) {
                    goldList.remove(2);
                }
                if (data.getLinePromote_gold_semi_switch().equals("0")) {
                    goldList.remove(1);
                }
                if (data.getLinePromote_gold_annual_switch().equals("0")) {
                    goldList.remove(0);
                }
                if (data.getLinePromote_gold_switch().equals("0")) {
                    goldList.clear();
                }
                if (MyUtils.isEmpty(goldList)) {
                    mLlGoldCard.setVisibility(View.GONE);
                    mIvSilverLabel.setVisibility(View.VISIBLE);
                } else {
                    select(0);
                }


                //银卡价格
                silverList.add(new PromotionPrice("年度推广", "6", "银卡推广"));
                silverList.add(new PromotionPrice("半年推广", "7", "银卡推广"));
                silverList.add(new PromotionPrice("季度推广", "8", "银卡推广"));
                silverList.get(0).setOriginalCost(data.getLinePromote_silver_annual_originalMoney());
                silverList.get(0).setPresentPrice(data.getLinePromote_silver_annual_nowMoney());
                silverList.get(1).setOriginalCost(data.getLinePromote_silver_semi_originalMoney());
                silverList.get(1).setPresentPrice(data.getLinePromote_silver_semi_nowMoney());
                silverList.get(2).setOriginalCost(data.getLinePromote_silver_quarter_originalMoney());
                silverList.get(2).setPresentPrice(data.getLinePromote_silver_quarter_nowMoney());
                if (data.getLinePromote_silver_quarter_switch().equals("0")) {
                    silverList.remove(2);
                }
                if (data.getLinePromote_silver_semi_switch().equals("0")) {
                    silverList.remove(1);
                }
                if (data.getLinePromote_silver_annual_switch().equals("0")) {
                    silverList.remove(0);
                }
                if (data.getLinePromote_silver_switch().equals("0")) {
                    silverList.clear();
                }
                if (MyUtils.isEmpty(silverList)) {
                    mLlSilverCard.setVisibility(View.GONE);
                    mIvGoldLabel.setVisibility(View.VISIBLE);
                } else {
                    if (mLlGoldCard.getVisibility() == View.GONE) {
                        mLlSilverCard.performClick();
                    }
                }
            }
        } else {
            AdvancePayment payment = new Gson().fromJson(json, AdvancePayment.class);
            if (payment.isStatus()) {
                startActivity(new Intent(mActivity, PayDeskActivity.class)
                        .putExtra("pay_sn", payment.getData().getOrder_id())
                        .putExtra("money", String.valueOf(money))
                        .putExtra("type", payType)
                        .putExtra("promote_type", type));
            } else {
                ToastUtil.show(payment.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Subscribe
    public void onEvent(PayStatus event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}